import {
  _decorator,
  Component,
  Node,
  Input,
  __private,
  EventTouch
} from 'cc'
import { GameManager } from '../framework/GameManager'
const { ccclass, property, menu } = _decorator

/**
 * Predefined variables
 * Name = UIMain
 * DateTime = Thu Feb 10 2022 18:57:46 GMT+0800 (中国标准时间)
 * Author = ashscc
 * FileBasename = UIMain.ts
 * FileBasenameNoExtension = UIMain
 * URL = db://assets/script/ui/UIMain.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/en/
 *
 */

@ccclass('UIMain')
@menu('ui/UIMain')
export class UIMain extends Component {
  @property
  public speed: number = 1

  @property(Node)
  public playerPlane: Node = null
  @property(GameManager)
  public gameManager: GameManager = null
  @property(Node)
  public gameStart: Node = null
  @property(Node)
  public game: Node = null
  @property(Node)
  public gameOver: Node = null

  start() {
    this.node.on(Input.EventType.TOUCH_START, this._onTouchStart, this)
    this.node.on(Input.EventType.TOUCH_MOVE, this._onTouchMove, this)
    this.node.on(Input.EventType.TOUCH_END, this._onTouchEnd, this)

    this.gameStart.active = true
  }
  
  public restart(){
    this.gameManager.play('button')
    this.gameOver.active = false
    this.game.active = true
    this.gameManager.gameRestart()
  }

  public returnMain(){
    this.gameManager.play('button')
    this.gameOver.active = false
    this.gameStart.active = true
    this.gameManager.returnMain()
  }

  private _onTouchMove(event: EventTouch) {
    if(this.gameManager.isGameStart){
      const delta = event.getDelta()
      let pos = this.playerPlane.position
      this.playerPlane.setPosition(
        pos.x + 0.01 * delta.x * this.speed,
        pos.y,
        pos.z - 0.01 * delta.y * this.speed
      )
    }
  }

  private _onTouchStart(event: EventTouch){
    if(this.gameManager.isGameStart){
      this.gameManager.isShooting(true)
    }else {
      this.gameManager.play('button')
      this.gameStart.active = false
      this.game.active = true
      this.gameManager.gameStart()
    }
  }

  private _onTouchEnd(event: EventTouch){
    if(this.gameManager.isGameStart) {
      this.gameManager.isShooting(false)
    }
  }
  // update (deltaTime: number) {
  //     // [4]
  // }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/en/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/en/scripting/life-cycle-callbacks.html
 */
